class: center, middle, inverse, title-slide .title[ #
] .author[ ### ] --- class: center, middle, animated, bounceInDown #### Theory lessons <br> | Marta Coronado Zamora | Jose F. Sánchez | |:-:|:-:| | <a href="mailto:Marta.coronado@uab.cat"><i class="fa fa-paper-plane fa-fw"></i> marta.coronado@uab.cat</a> | <a href="mailto:JoseFrancisco.Sanchez@uab.cat"><i class="fa fa-paper-plane fa-fw"></i> josefrancisco.sanchez@uab.cat</a> | | <a href="https://bsky.app/profile/geneticament.bsky.social"><i class="fab fa-bluesky fa-fw"></i> @geneticament</a> | <a href="https://twitter.com/JFSanchezBioinf"><i class="fab fa-twitter fa-fw"></i> @JFSanchezBioinf</a> | | <a href="https://portalrecerca.uab.cat/es/organisations/grup-de-gen%C3%B2mica-bioinform%C3%A0tica-i-biologia-evolutiva-gbbe/"><i class="fa fa-map-marker fa-fw"></i> Universitat Autònoma de Barcelona </a> | <a href="http://www.germanstrias.org/technology-services/genomica-bioinformatica/"> <i class="fa fa-map-marker fa-fw"></i>Germans Trias i Pujol Research Institute (IGTP)</a> | #### Practical lessons <br> | Miriam Merenciano | |:-:| | <a href="mailto:miriam.merenciano@uab.cat"><i class="fa fa-paper-plane fa-fw"></i> miriam.merenciano@uab.cat </a> | | <a href="https://portalrecerca.uab.cat/es/organisations/grup-de-gen%C3%B2mica-bioinform%C3%A0tica-i-biologia-evolutiva-gbbe/"><i class="fa fa-map-marker fa-fw"></i> Universitat Autònoma de Barcelona </a> | <style> .title-slide { background-image: url('img/1.png'); background-size: 100%; } </style> --- layout: true class: animated, fadeIn --- # Theory session dynamics __Content__ - Theory - Examples and short exercises in class (<i class="fas fa-pencil-alt"></i>) - complete and submit to [Atenea](https://atenea.upc.edu/course/view.php?id=105474) <i class="fas fa-laptop-code"></i> _Bring your laptop to theory sessions!_ **Interactive <i class="fab fa-r-project fa-fw"></i></i> documents** `R code` can be executed within RStudio! ``` r value <- 2 value + 3 ``` ``` ## [1] 5 ``` --- layout: false class: left, bottom, inverse, animated, bounceInDown # Get started! ## Graphics with `ggplot2` --- layout: true class: animated, fadeIn --- # The grammar of graphics .pull-left[ #### Original grammar <i class="fas fa-book"></i> Wilkinson, Leland. The grammar of graphics. Springer Science & Business Media, 2006. ] .pull-right[ <center>  ] -- #### Adapted to `R` in the `ggplot2` package <i class="fas fa-book"></i> Hadley Wickham. ggplot2: elegant graphics for data analysis. Springer, 2009. <small><br> "The grammar tells us that a __statistical graphic is a mapping from data to aesthetic attributes__ (colour, shape, size) __of geometric objects__ (points, lines, bars). The plot may also contain __statistical transformations__ of the data and is drawn on a specific __coordinate system__. __Facetting__ can be used to generate the same plot for different subsets of the dataset. It is the combination of these independent components that make up a graphic." --- ## Syntax In `ggplot2` there are different components we can add to a plot: .pull-left[ ```r ggplot(data = <DATA>, mapping = aes(<MAPPINGS>)) + <GEOM_FUNCTION>(stat = <STAT>, position = <POSITION>) + <SCALE_FUNCTION>() + <COORDINATE_FUNCTION>() + <FACET_FUNCTION>() + <THEME_FUNCTION> ``` ] <img src="img/ggplot2layers2019_8_10D11_28_23.png" width="52%" style="position: absolute; right: 50px; top: 25%;"> <center> <p style="position:absolute; bottom:125px; right:200px;"> Grammar of Graphics:<br>A layered approach to elegant visuals </p> --- ## Components The layered grammar defines a plot as a combination of: - __Layers__ + Data + Aesthetic mapping + Geometric objects + Statistical transformation + Position adjustment - __Scales__ - __Coordinate system__ - __Faceting specification__ - __Theme__ (not in the original grammar) <img src="img/ggplot2layers2019_8_10D11_28_23.png" width="52%" style="position: absolute; right: 50px; top: 25%;"> <center> <p style="position:absolute; bottom:125px; right:200px;"> Grammar of Graphics:<br>A layered approach to elegant visuals --- ### Layers **Layers** are responsible for creating the objects that we perceive on the plot. - __Data__ - __Aesthetic mapping__ - __Geometric objects__ - __Statistical transformation__ - __Position adjustment__ -- #### Syntax: ``` r ggplot(data = data, mapping = aes(x = var1, y = var2, colour = var3)) + layer(geom = "point", stat = "identity", position = "identity") ``` --- ### Layers: Data The data layer specifies the data being plotted. Must be an **R data frame** object. ``` r head(iris, 5) ``` ``` ## Sepal.Length Sepal.Width Petal.Length Petal.Width Species ## 1 5.1 3.5 1.4 0.2 setosa ## 2 4.9 3.0 1.4 0.2 setosa ## 3 4.7 3.2 1.3 0.2 setosa ## 4 4.6 3.1 1.5 0.2 setosa ## 5 5.0 3.6 1.4 0.2 setosa ``` -- ``` r ggplot(data = iris) ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-4-1.png" alt="" width="180" style="display: block; margin: auto;" /> We get a blank square because we have not added any other layers yet! --- ### Layers: mapping data onto aesthetics The `iris` data frame has different columns: **aesthetics**. The aesthetic layer, or aes for short, specifies how we want to map our data onto the scales of the plot (such as the `x` and `y` coordinates). -- In `ggplot2` the aesthetic layer is specified using the `aes()` function. ``` r ggplot(data = iris, mapping = aes(x = Sepal.Width, y = Sepal.Length)) ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-5-1.png" alt="" width="180" style="display: block; margin: auto;" /> The graph shows variable and scales of `Sepal.Length` mapped onto the `x`-axis and `Sepal.Width` on the `y`-axis. What are we missing? -- A **geom**! --- ### Layers: mapping data onto aesthetics The **geom** is the geometric object to use display the data. ``` r ggplot(data = iris, mapping = aes(x = Sepal.Width, y = Sepal.Length)) + geom_point() ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-6-1.png" alt="" width="324" style="display: block; margin: auto;" /> Now we have a scatterplot of the relationship between `Sepal.Length` and `Sepal.Width`. --- ### Layers: mapping data onto aesthetics #### Main aesthetics types: <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-7-1.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-7-2.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-7-3.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-7-4.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-7-5.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-7-6.png" alt="" width="324" /> #### <i class="fas fa-pencil-alt"></i> **Exercise** | Which aesthetic attributes can a continuous variable be mapped to? And a discrete variable? --- ### Layers: mapping data onto aesthetics Data and mapping can be defined in the initial `ggplot()` call or in the layer (`geom_` or `stat_`) ``` r # Default data and mapping used by the layer ggplot(data = iris, mapping = aes(x = Sepal.Width, y = Sepal.Length)) + geom_point() # No default defined, data and mapping in layer ggplot() + geom_point(data = iris, mapping = aes(x = Sepal.Width, y = Sepal.Length)) ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-9-1.png" alt="" width="216" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-9-2.png" alt="" width="216" /> #### <i class="fas fa-pencil-alt"></i> **Exercise** | With the code that generate the previous figure, experiment with the colour, size, transparency (<code>alpha</code>) and shape aesthetics. <div style="background-color:#F0F0F0">  <i class="fas fa-comment-dots"></i> Answer:   </div> --- ### Layers: mapping data onto aesthetics All variables used in the plot should be in the data. ``` r # Correct ggplot(iris, aes(x = Sepal.Width, y = Sepal.Length)) + geom_point() # Not recommended ggplot(iris, aes(x = Sepal.Width, y = iris$Sepal.Length)) + geom_point() SL_var <- iris$Sepal.Length ggplot(iris, aes(x = Sepal.Width, y = SL_var)) + geom_point() ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-11-1.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-11-2.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-11-3.png" alt="" width="324" /> --- ### Layers: mapping data onto aesthetics #### <i class="fas fa-pencil-alt"></i> **Exercise** | Simplify the following code. ``` r ggplot(mpg) + geom_point(aes(mpg$displ, mpg$hwy)) ggplot() + geom_point(mapping = aes(y = hwy, x = cty), data = mpg) + geom_smooth(data = mpg, mapping = aes(cty, hwy)) ggplot(diamonds, aes(carat, price)) + geom_point(aes(log(brainwt), log(bodywt)), data = msleep) ``` --- ### Layers: mapping data onto aesthetics #### Mapping (variable) vs. setting (constant) ``` r p <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) p + geom_point(aes(colour = Species)) # Map Species to colour p + geom_point(aes(colour = "darkblue")) # Map "darkblue" to colour p + geom_point(colour = "darkblue") # Set colour to "darkblue" ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-13-1.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-13-2.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-13-3.png" alt="" width="324" /> --- ### Layers: mapping data onto aesthetics __Group__ aesthetic: by default it is the combination of discrete variables (except position). #### Multiple groups, one aesthetic: ``` r ggplot(nlme::Oxboys, aes(age, height)) + geom_line() ggplot(nlme::Oxboys, aes(age, height, group = Subject)) + # or colour = Subject geom_line() ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-14-1.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-14-2.png" alt="" width="324" /> --- ### Layers: mapping data onto aesthetics __Group__ aesthetic: by default it is the combination of discrete variables (except position). #### Different groups on different layers: ``` r ggplot(nlme::Oxboys, aes(age, height, group = Subject)) + geom_line() + geom_smooth(aes(group = Subject)) ggplot(nlme::Oxboys, aes(age, height, group = Subject)) + geom_line() + geom_smooth(aes(group = 1)) # o group = NULL ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-15-1.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-15-2.png" alt="" width="324" /> --- ### Layers: mapping data onto aesthetics #### <i class="fas fa-pencil-alt"></i> **Exercise** | Are the observations grouped in the following plot? If so, what variables are used for the grouping? <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-16-1.png" alt="" width="324" style="display: block; margin: auto;" /> --- ### Layers: mapping data onto aesthetics - Aesthetic attributes: + __Position__: x, y, xmin, xmax, ymin, ymax, xend, yend + __Colour__: colour, fill, alpha + __Differentiation__: shape, size, linetype + __Grouping__: group - Each geom understands a different set of aesthetics - Each geom requires some aesthetics (`?geom_*`) --- ### Layers: geometric objects <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-17-1.png" alt="" width="205.2" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-17-2.png" alt="" width="205.2" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-17-3.png" alt="" width="205.2" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-17-4.png" alt="" width="205.2" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-17-5.png" alt="" width="205.2" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-17-6.png" alt="" width="205.2" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-17-7.png" alt="" width="205.2" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-17-8.png" alt="" width="205.2" /> #### <i class="fas fa-pencil-alt"></i> **Exercise** | Which geoms are collective? (multiple observations share a geometrical object) --- ### Layers: geometric objects - Full list of geom_* functions: + [ggplot2 reference](https://ggplot2.tidyverse.org/reference/index.html#section-layer-geoms) + [ggplot2 cheat sheet](https://raw.githubusercontent.com/rstudio/cheatsheets/main/data-visualization.pdf), sorted by type --- ### Layers: statistical transformation The statistics layer allows you plot statistical values calculated from the data. Transforms the data, typically by summarising it in some manner. A stat takes a dataset as input and returns a dataset as output, and so a stat can add new variables to the original dataset. <center> dataset <i class="fas fa-arrow-right"></i> statistical transformation <i class="fas fa-arrow-right"></i> dataset </center> ``` r ggplot(diamonds, aes(carat)) + geom_histogram(aes(y=after_stat(count)), binwidth = 0.1) ggplot(diamonds, aes(carat)) + geom_histogram(aes(y=after_stat(density)), binwidth = 0.1) ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-18-1.png" alt="" width="216" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-18-2.png" alt="" width="216" /> New variables are accessed with `after_stat(var)` notation or `stat()` (v3.4.0+) --- ### Layers: statistical transformation ``` r p <- ggplot(mtcars, aes(x = factor(cyl))) p + geom_bar() + labs(title = "count") # uses stat = "bin" by default p + geom_bar(aes(y = after_stat(count)/sum(after_stat(count)))) + labs(title = "count/sum(count)") # p + geom_bar(aes(y = stat(count/sum(count)))) p + geom_bar(aes(y = after_stat(prop), group = 1)) + labs(title = "prop") ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-19-1.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-19-2.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-19-3.png" alt="" width="324" /> <i class="fas fa-info-circle"></i> Note that we need to specify `group = 1` (or `group = NULL`), otherwise the proportion are calculated within each group and therefore all proportions would be 1. --- ### Layers: statistical transformation - Full list of stat_* functions: + `ggplot2` reference: [geoms](https://ggplot2.tidyverse.org/reference/index.html#section-layer-geoms) and [stats](https://ggplot2.tidyverse.org/reference/index.html#section-layer-stats) + [`ggplot2` cheat sheet](https://raw.githubusercontent.com/rstudio/cheatsheets/main/data-visualization.pdf) - New variables from statistical transformations: + `stat_count`: count, prop + `stat_bin` or `stat_bin2d`: count, density + `stat_boxplot`: width, ymin, ymax, middle + `stat_smooth`: y, ymin, ymax, se + `stat_summary`: value --- ### Layers: position adjustment Position adjustments apply minor tweaks to the position of elements within a layer. ``` r p <- ggplot(mtcars, aes(x = factor(cyl), y = mpg, colour = factor(cyl))) p + geom_point() + labs(title = "identity") # default point position p + geom_point(position = "jitter") + labs(title = "jitter") p + geom_point(position = position_nudge(x = 0.3)) + labs(title = "nudge") ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-20-1.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-20-2.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-20-3.png" alt="" width="324" /> --- ### Layers: position adjustment Position adjustments apply minor tweaks to the position of elements within a layer. ``` r b <- ggplot(mtcars, aes(x = factor(cyl), fill = factor(gear))) b + geom_bar() + labs(title="stack") # default bar position b + geom_bar(position = "fill") + labs(title="fill") b + geom_bar(position = "dodge") + labs(title="dodge") ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-21-1.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-21-2.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-21-3.png" alt="" width="324" /> --- ### Layers: data + aes + geom + stat + position |fun |aes |geom |stat |position | |:-----------|:-----------------------------------|:------|:--------|:--------| |geom_point |x, y, alpha, colour, size, shape... |point |identity |identity | |geom_line |x, y, linetype... |line |identity |identity | |geom_ribbon |x, ymin, ymax... |ribbon |identity |identity | |geom_col |x, y, ... |col |identity |stack | |geom_text |x, y, label, angle, fontface... |text |identity |identity | |stat_ecdf |x, colour, linetype |step |ecdf |identity | --- ### Layers: type of layers and annotations We can add additional **metadata**, context and annotations, that help to give meaning to the raw data or highlight important features. ``` r ggplot(iris, aes(x = Species, y = Petal.Width, colour = Species)) + # Show data geom_jitter(show.legend = FALSE) + # Summarize geom_boxplot(fill = NA, show.legend = FALSE) + # Annotate geom_hline(yintercept = mean(iris$Petal.Width), alpha = 0.5) ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-23-1.png" alt="" width="360" style="display: block; margin: auto;" /> --- ### Layers: type of layers and annotations - Common `geom_*` functions with metadata: + `geom_text()`, `geom_rect()`, `geom_point()` + `geom_line()`, `geom_path()`, `geom_segment()` .pull-left[ ``` r p <- ggplot(mtcars, aes(hp, mpg)) + geom_point() p + # Add red cercles geom_point(data = mtcars[mtcars$hp > 300 | mtcars$mpg > 30,], colour = "red", shape = 1, size = 7) + # Draw an arrow geom_segment(data = mtcars[mtcars$hp > 100 & mtcars$mpg > 30,], aes(xend = hp + 30, yend = mpg + 3), arrow = arrow(ends = "first", type = "closed", angle = 15, length = unit(0.5,"cm")), colour = "gray50") + # Add text geom_text(data = mtcars[mtcars$hp > 100 & mtcars$mpg > 30,], aes(label = "Economical car"), position = position_nudge(x = 30, y = 3), hjust = 0) ``` ] .pull-right[ <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-25-1.png" alt="" width="432" style="display: block; margin: auto;" /> ] --- ### Layers: type of layers and annotations - Special layers that act as normal geoms if parameters are within `aes()` or as annotations if outside. + `geom_vline()`, `geom_hline()`, `geom_abline()` - Special layers that don't inherit global settings + `annotate()`, `annotation_custom()` .pull-left[ ``` r # Represent mpg vs. hp and annotate a subset of points with a rectangle p_overview <- ggplot(mtcars, aes(hp, mpg)) + annotate(geom = "rect", xmin = 50, ymin = 25, xmax = 100, ymax = 35, fill = "red", alpha = 0.3 )+ geom_point() + labs(x = NULL, y = NULL) # Represent the subset of points p_subset <- ggplot(mtcars[mtcars$hp <100 & mtcars$mpg >25,], aes(hp, mpg)) + geom_point() # Add an inset with the full data p_subset + annotation_custom(ggplotGrob(p_overview), xmin = 75, ymin = 30) ``` ] .pull-right[ <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-27-1.png" alt="" width="432" style="display: block; margin: auto;" /> ] --- ### Layers: type of layers and annotations #### <i class="fas fa-pencil-alt"></i> **Exercise** | Exercise: what type of annotation is the most appropriate for the following cases: A. To highlight some points B. To add the expected linear trend C. To write some text --- ### Scales Scales control the mapping from data to aesthetics. They take your data and turn it into something that you can perceive visually: e.g., size, colour, position or shape. - Types of scales + Axis: `x` and `y` position + Legend: the other aesthetics (fill, alpha, shape...) - Default scales + `scale_<aes>_continuous()`: map continious values to visual values + `scale_<aes>_discrete()`: map discrete values to visual values - Manual scales for discrete variables + `scale_<aes>_manual(values = c(1, 2, 4))`: map pdiscrete values to manualy chosen visual values --- ### Scales In all scales you can define: `name`, `breaks` and `labels`. ``` r ggplot(mtcars, aes(x = mpg, y = wt, shape = factor(gear))) + geom_point() + scale_y_continuous(name = "Weight", breaks = c(2.5,5)) + scale_x_continuous(name = quote(frac(miles, gallon))) + scale_shape_discrete(name = "Type", labels = c("III","IV","V")) ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-29-1.png" alt="" width="396" style="display: block; margin: auto;" /> --- ### Scales: legends - Can be turned on/off - Need the same name, breaks and labels to be merged ``` r p <- ggplot(mtcars, aes(x = mpg, y = wt, shape = factor(gear), colour = factor(gear))) p + geom_point() p + geom_point(show.legend = FALSE) p + geom_point() + scale_shape_discrete(name = "Type", labels = c("III","IV","V")) + scale_colour_discrete(name = NULL) ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-30-1.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-30-2.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-30-3.png" alt="" width="324" /> --- ### Scales: continuous axes ``` r p <- ggplot(mtcars, aes(hp, mpg)) + geom_point() p + labs(title = "untransformed") p + scale_x_continuous(trans = "log10") + labs(title = "log(x)") p + scale_y_reverse() + labs(title = "rev(x)") ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-31-1.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-31-2.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-31-3.png" alt="" width="324" /> --- ### Scales: colour scales for discrete variables <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-32-1.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-32-2.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-32-3.png" alt="" width="324" /> --- ### Scales: colour scales for continuous variables <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-33-1.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-33-2.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-33-3.png" alt="" width="324" /> --- ### Coordinate system The coordinate component allows you to adjust the `x` and `y` coordinates. <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-34-1.png" alt="" width="288" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-34-2.png" alt="" width="288" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-34-3.png" alt="" width="288" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-34-4.png" alt="" width="288" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-34-5.png" alt="" width="288" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-34-6.png" alt="" width="288" /> --- ### Coordinate system ####Zoom ``` r p <- ggplot(data = data.frame(x = c(1,2.5,3,3.5,5,3.5,3,2.5,1), y = c(3,3.5,5,3.5,3,2.5,1,2.5,3)), aes(x, y)) + geom_polygon() p + labs(title = "Full") p + coord_cartesian(xlim = c(2,4)) + labs(title = "Image clipped") ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-35-1.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-35-2.png" alt="" width="324" /> --- ### Coordinate system #### Maps ``` r # install.packages("maps"); library(maps) if(require("maps")){ worldmap <- map_data(map = "world") ggplot(worldmap, aes(x = long, y = lat, group = group)) + geom_polygon(fill = "gray20", colour = "gray92") + coord_quickmap() } ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-36-1.png" alt="" width="360" style="display: block; margin: auto;" /> - `coord_map` can use projections from package `mapproj` (needs to be installed) --- ### Facets Faceting is a mechanism for automatically laying out multiple plots on a page. It splits the data into subsets, and then plots each subset into a different panel on the page. Such plots are often called small multiples. ``` r p <- ggplot(mtcars, aes(x = wt, y = mpg, colour = factor(cyl), shape = factor(am))) + geom_point(show.legend = FALSE) + labs(x = NULL, y = NULL) p p + facet_wrap(~factor(cyl)) # 1d ribbon of panels that is wrapped into 2d p + facet_grid(factor(am) ~ factor(cyl)) # 2d grid of panels defined by variables which form the rows and columns ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-37-1.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-37-2.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-37-3.png" alt="" width="324" /> --- ### Facets `facet_grid` have two additional arguments: `scales` and `space`. ``` r msleep$name <- factor(msleep$name, levels = msleep$name[order(msleep$sleep_total)]) p <- ggplot(msleep[msleep$vore %in% c("carni","insecti"), ], aes(x = sleep_total, y = name)) + geom_point() + scale_x_log10() p + facet_grid(vore~.) p + facet_grid(vore~., scales = "free", space = "free") ``` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-38-1.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-38-2.png" alt="" width="324" /> --- ### Themes - Complete themes `theme_*()` - Theme elements `theme()` <img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-39-1.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-39-2.png" alt="" width="324" /><img src="data:image/png;base64,#1_files/figure-html/unnamed-chunk-39-3.png" alt="" width="324" /> - Full list of theme elements: `?theme` --- ## Components The layered grammar defines a plot as a combination of: - __Layers__ + Data + Aesthetic mapping + Geometric objects + Statistical transformation + Position adjustment - __Scales__ - __Coordinate system__ - __Faceting specification__ - __Theme__ (not in the original grammar) <img src="img/ggplot2layers2019_8_10D11_28_23.png" width="52%" style="position: absolute; right: 50px; top: 25%;"> <center> <p style="position:absolute; bottom:125px; right:200px;"> Grammar of Graphics:<br>A layered approach to elegant visuals --- ## Components #### <i class="fas fa-pencil-alt"></i> **Exercise** | Update the plot to match the requirements below ``` r p <- ggplot(msleep, aes(x = vore, y = sleep_total, colour = vore, fill = vore)) + geom_violin(alpha = 0.2, colour = NA) + geom_jitter(width = 0.3) ``` - Legend on top of the plot - White background - No ticks in y axis - Axis labels rotated to an angle of 45 degrees <i class="fas fa-key"></i> Note: check `?theme` options --- ## Components #### <i class="fas fa-pencil-alt"></i> **Exercise** | Update the plot to match the requirements below --- layout: false class: inverse, center, middle, animated, bounceInDown ### Upload `1.Rmd` with the completed exercises (text included) to [Atenea](https://atenea.upc.edu/course/view.php?id=105474)